import { Component, OnInit, Input, Output, EventEmitter, ElementRef } from '@angular/core'
import { JsonApiService } from 'app/core/api/json-api.service' //http请求配置引入
import { config } from '../smartadmin.config'
import { Router } from '@angular/router'

declare var $: any
var pinyin = require('pinyin')
@Component({
  selector: 'sa-company-tree-car',
  templateUrl: './companyTreeCar.component.html',
  styleUrls: ['./companyTreeCar.component.css']
})
export class CompanyTreeCarComponent implements OnInit {
  @Input() companyTreeId: string //公司树标识Id
  @Input() tcarTypeSelect2: string = 'TcarTypeSelect2' //车辆分类的标识id
  @Input() tcarNumberSelect2: string = 'carNumberSelect2' //车牌号的标识id
  @Input() wrap: any //事件页面根元素
  @Input() wrapId: any //事件页面根元素Id
  @Input() companyData: any //父组件公司数据
  @Input() Height: number //高度
  @Input() inputName: string = 'companyName' //校验使用的公司名称;默认name="companyName"
  @Input() placeholder: string = '请选择' //弱提示语
  @Output() companySelected = new EventEmitter()
  @Input() noCar: boolean // 条件为true 时不显示选择车辆
  @Input() preNext: boolean // 条件为true 时可以上下选择车辆
  @Input() isShowCarSort: boolean = false //是否显示车辆分类,默认不显示
  @Input() isShowCarNum: boolean = true //是否显示车辆分类,默认不显示
  @Input() isLinkCompanyAndCar: boolean = true //公司和车辆是否关联,默认关联
  @Input() sourceUrl: string = 'company/companytree.html' //默认公司接口地址
  @Input() sourceCarUrl: string = 'stats/carListByCarNumber.html' //默认 为全部车辆
  @Input() typeFlag: string = '' //1 离线明细; 2故障问题明细; 4重量异常明细; 5车辆清运统计; 5车辆清运明细; 7设备安装记录; 8设备维修记录
  @Input() title: string = '公司名称' //
  @Input() hasEmpty: boolean = false
  companyName: string = '' //选中的公司名称
  companyId: string = '' //选中的公司ID
  formCompanyName: string = '' // 表单中的公司树选中的公司名称
  formCompanyId: string = '' // 表单中的公司树选中的公司id
  deviceId: string = '' //设备ID
  carNumber: string = '' //车牌号码
  selectIndex: any = '' // 选中的位置
  selectCount: any = '' // 选中的总数
  clearTimer: any = '' // 定时器id
  carTypeList = carTypeListObj.carTypeList
  constructor(private jsonApiService: JsonApiService, private el: ElementRef, private router: Router) {}
  //传参给父组件
  sendParent() {
    let companyInfo = {
      companyName: this.companyName,
      companyId: this.companyId,
      deviceId: this.deviceId,
      carNumber: this.carNumber,
      useTypeL2: $('#' + this.tcarTypeSelect2).val() ? $('#' + this.tcarTypeSelect2).val() : '',
      useTypeL1: $('#' + this.tcarTypeSelect2).val()
        ? $('#' + this.tcarTypeSelect2)
            .val()
            .slice(0, 2)
        : ''
    }
    this.companySelected.emit(companyInfo)
  }
  ngOnInit() {
    System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
      System.import('assets/js/select2-zh-CN.js').then(() => {
        this.select2Car() //初始化select 2 车辆
        this.carSortSelectChange()
      })
      System.import('assets/js/jstree/jstree.min.js').then(() => {
        this.initCompanyList()
        this.companyCilckEvent()
      })
    })
  }
  ngOnChanges() {
    let that = this

    if (this.companyData && this.companyData.companyId) {
      this.companyName = this.companyData.companyName
      this.companyId = this.companyData.companyId
      System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
        System.import('assets/js/select2-zh-CN.js').then(() => {
          that.queryCarListByCompanyId(that.companyData.companyId)
        })
      })
      $('#' + this.companyTreeId)
        .find('.tree_company_input')
        .val(this.companyData.companyName)
        .change()
    }
    // 没有公司直接搜索车牌号选择然后进行查询的情况
    if (this.companyData && this.companyData.deviceId && !this.companyData.companyId) {
      this.deviceId = this.companyData.deviceId
      this.carNumber = this.companyData.carNumber
      var carOption = $('<option>')
      carOption.attr('value', this.companyData.deviceId)
      carOption.text(this.companyData.carNumber)
      $('#' + this.tcarNumberSelect2).append(carOption)
      $('#' + this.tcarNumberSelect2)
        .val(this.companyData.deviceId)
        .trigger('change')
      // 显示之后再将这条数据删除 不然再选择公司会存留数据
      this.companyData.deviceId = ''
      this.companyData.carNumber = ''
    }
    if (this.companyData && this.companyData.useTypeL2) {
      setTimeout(() => {
        $('#' + this.tcarTypeSelect2)
          .val(this.companyData.useTypeL2)
          .trigger('change')
      }, 1)
      // this.sendParent();
    }
  }
  //车辆分类选择回调
  carSortSelectChange() {
    $('#' + this.tcarTypeSelect2)
      .select2({ language: 'zh-CN' })
      .on(
        'select2:select',
        function (e) {
          this.sendParent()
        }.bind(this)
      )
  }
  //页面点击事件监听
  companyCilckEvent() {
    let companyTreeM = document.getElementById(this.companyTreeId)
    let tree_box = companyTreeM.getElementsByClassName('s_tree_box')[0]
    let company = companyTreeM.getElementsByClassName('tree_company_input')[0]
    // 如果传了wrapId就用wrapId绑定事件 如果没有传  就用wrap  wrap没传就用document
    let wrap: any = this.wrapId
      ? document.getElementById(this.wrapId)
      : this.wrap
      ? document.getElementsByTagName(this.wrap)
      : document
    wrap.onclick = function (e: any) {
      if (tree_box.contains(e.target) || e.target == company) {
        //判断点击是否在下拉框内
        if (
          e.target.className == 'jstree-anchor jstree-hovered jstree-clicked' ||
          e.target.className == 'jstree-icon jstree-themeicon fa fa-home jstree-themeicon-custom' ||
          e.target.className == 'jstree-anchor jstree-hovered jstree-clicked jstree-search' ||
          e.target.className == 'jstree-anchor jstree-clicked' ||
          e.target.className == 'jstree-anchor jstree-search jstree-hovered jstree-clicked'
        ) {
          tree_box.className = tree_box.className.replace('tree_open', '')
        }
      } else if (e.target.className == 'form-control ng-pristine ng-valid ng-touched') {
        // tree_box.className=tree_box.className+" tree_open";
      } else {
        tree_box.className = tree_box.className.replace('tree_open', '')
      }
    }
  }
  ngOnDestroy() {
    let wrap: any = this.wrapId
      ? document.getElementById(this.wrapId)
      : this.wrap
      ? document.getElementsByTagName(this.wrap)
      : document
    wrap.onclick = null
  }
  //拉取公司数据,生成树形图
  initCompanyList() {
    var that = this
    $('#' + this.companyTreeId)
      .find('.treeId')
      .eq(0)
      .jstree({
        core: {
          data: function (obj, callback) {
            var jsonstr = '[]'
            var jsonarray = eval('(' + jsonstr + ')')
            var url = that.sourceUrl
            $.ajax({
              type: 'GET',
              url: config.BaseURL + url,
              dataType: 'json',
              xhrFields: {
                withCredentials: true
              },
              timeout: 30000,
              success: function (result) {
                // 增加公司拼音字段
                var forData = result.data ? result.data : result
                if (forData.length) {
                  for (let i = 0; i < forData.length; i++) {
                    forData[i].text =
                      forData[i].text +
                      `<span style="display: none;">${pinyin(forData[i].text, { style: pinyin.STYLE_NORMAL }).join(
                        ''
                      )}</span>`
                  }
                  if (that.hasEmpty) {
                    // 可以选择没有所属项目，默认 id 是 ' '
                    forData.unshift({
                      parent: "#",
                      text: '所属项目为空' + `<span style="display: none;">${pinyin('所属项目为空', { style: pinyin.STYLE_NORMAL }).join(
                        ''
                      )}</span>`,
                      id: '空白',
                      icon: "fa fa-hashtag"
                    })
                  }
                }

                jsonarray = result
                callback.call(this, jsonarray)
              },
              error: function (data, errorMsg) {
                if (data.statusText === 'timeout') {
                  this.jsonApiService.message('请求超时,请重试')
                } else {
                  common.clearCookie('isLogin')
                  common.clearCookie('WEBSIDE_SID')
                  localStorage.clear()
                  this.router.navigate(['/auth'])
                }
              }
            })
          },

          themes: {
            responsive: true
          },
          multiple: false,
          animation: 200,
          dblclick_toggle: true,
          expand_selected_onload: true
        },
        plugins: ['search']
      })
      .bind('activate_node.jstree', function (e, obj) {
        var currentNode = obj.node // 获取当前节点
        that.companyName = currentNode.text.substring(0, currentNode.text.indexOf('<')) // 获取内容前删除添加的拼音字段
        that.companyId = currentNode.id
        $('#' + that.companyTreeId)
          .find('.tree_company_input')
          .val(that.companyName)
          .change()
        if (that.isLinkCompanyAndCar) {
          that.queryCarListByCompanyId(currentNode.id)
        }
        that.companySearch()
        that.sendParent()
        if ($('#' + that.companyTreeId).find('.jstree-searchCheck').length > 0) {
          if (
            $('#' + that.companyTreeId).find('.jstree-searchCheck')[0].className ==
              'jstree-anchor jstree-search jstree-searchCheck' ||
            $('#' + that.companyTreeId).find('.jstree-searchCheck')[0].className ==
              'jstree-anchor jstree-searchCheck jstree-hovered jstree-clicked'
          ) {
            $('#' + that.companyTreeId).find('.s_tree_box')[0].className = 's_tree_box'
            that.selectIndex = ''
            that.selectCount = ''
          }
        } else {
          if (that.companyName) {
            $('#' + that.companyTreeId).find('.s_tree_box')[0].className = 's_tree_box'
          }
        }
      })
  }

  //擦除公司所选值
  delText() {
    this.companyName = ''
    this.companyId = ''
    this.deviceId = ''
    this.carNumber = ''
    this.clearSelect2($('#' + this.tcarNumberSelect2)) //清除Select中的数据
    this.select2Car()
    $('#' + this.companyTreeId)
      .find('.treeSearchInput')
      .val('')
    $('#' + this.companyTreeId)
      .find('.tree_company_input')
      .val('')
      .change()
    this.companySearch()
    if (
      $('#' + this.companyTreeId)
        .find('.s_tree_box')[0]
        .className.indexOf('tree_open') > 0
    ) {
      $('#' + this.companyTreeId)
        .find('.tree_company_input')
        .focus()
    }
    this.selectIndex = ''
    this.selectCount = ''
    if ($('#' + this.companyTreeId).find('.jstree-searchCheck').length != 0) {
      $('#' + this.companyTreeId).find('.jstree-searchCheck')[0].className = 'jstree-anchor'
    }
    this.sendParent()
  }

  resetData() {
    // 清除公司和车牌号
    this.delText()
    // 清除车辆分类
    var str = $("<span class='select2-selection__placeholder'>请选择</span>")
    $('#' + this.tcarTypeSelect2).val('')
    $('#select2-cartypeSelect2-container').empty()
    $('#select2-cartypeSelect2-container').attr('title', '')
    $('#select2-cartypeSelect2-container').prepend(str)
    this.sendParent()
    // 清除选中
    $('.jstree-anchor').removeClass('jstree-clicked')
  }
  //打开公司树
  companyClick() {
    $('#' + this.companyTreeId).find('.s_tree_box').toggleClass('tree_open')
    // this.selectIndex = ''
    // this.selectCount = ''
    // if ($('#' + this.companyTreeId).find('.jstree-searchCheck').length != 0) {
    //   $('#' + this.companyTreeId).find('.jstree-searchCheck')[0].className = 'jstree-anchor'
    // }
  }

  //公司树模糊搜索
  companySearch() {
    var that = this
    var value = $('#' + this.companyTreeId).find('.treeSearchInput').val()

    that.selectIndex = ''
    that.selectCount = ''
    // for (var j = 0; j < $('#' + this.companyTreeId).find('.jstree-anchor').length; j++) {
    //   $('#' + this.companyTreeId).find('.jstree-anchor')[j].className = 'jstree-anchor'
    // }

    const oldSearchCheckElList = $('#' + this.companyTreeId).find('.jstree-searchCheck')
		if(oldSearchCheckElList.length > 0) {
		  for (var j = 0; j <oldSearchCheckElList.length; j++) {
			  oldSearchCheckElList[j].className = 'jstree-anchor'
		  }
		}

    if (this.clearTimer) {
      clearTimeout(this.clearTimer)
    }
    this.clearTimer = setTimeout(function () {
      $('#' + that.companyTreeId)
        .find('.treeId')
        .eq(0)
        .jstree(true)
        .search(value)
      let searchResult = $('#' + that.companyTreeId).find('.jstree-search').length
      if (searchResult < 1) {
        that.selectIndex = ''
        that.selectCount = ''
        return
      }

      if (value) {
        that.selectIndex = 1
        that.selectCount = $('#' + that.companyTreeId).find('.jstree-search').length
        $('#' + that.companyTreeId).find('.jstree-search')[0].className =
          'jstree-anchor jstree-search jstree-searchCheck'
      }

      $('#' + that.companyTreeId)
        .find('.jstree-search')
        .each(function (index, obj) {
          if (index < 1) {
            //js树搜索定位到结果的第一个地方；
            let container = $('#' + that.companyTreeId).find('.vision_tree')
            let scrollTo = $(this)
            container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop() - 130)
            container.animate({
              scrollTop:
                scrollTo.offset().top - container.offset().top + container.scrollTop() - container.height() * 0.3
            })
          }
        })
    }, 250)
  }
  upArrow() {
    var that = this
    if (parseInt(this.selectIndex) == 1) {
      that.jsonApiService.message('目前已经在开始位置')
      return
    }
    that.selectIndex = parseInt(that.selectIndex) - 1
    $('#' + that.companyTreeId).find('.jstree-search')[that.selectIndex - 1].className =
      'jstree-anchor jstree-search jstree-searchCheck'
    $('#' + that.companyTreeId).find('.jstree-searchCheck')[1].className = 'jstree-anchor jstree-search'

    let container = $('#' + that.companyTreeId).find('.vision_tree')
    let _this = $('#' + this.companyTreeId)
      .find('.jstree-search')
      .eq(that.selectIndex - 1)
    let top = _this.offset().top - container.offset().top + container.scrollTop() - container.height() * 0.3
    container.animate({ scrollTop: top })
  }
  downArrow() {
    var that = this
    if (parseInt(this.selectIndex) == parseInt(this.selectCount)) {
      that.jsonApiService.message('目前已经在结束位置')
      return
    }
    let lenindex = parseInt(this.selectIndex)
    $('#' + this.companyTreeId).find('.jstree-searchCheck')[0].className = 'jstree-anchor jstree-search '
    this.selectIndex = parseInt(this.selectIndex) + 1
    $('#' + this.companyTreeId).find('.jstree-search')[lenindex].className =
      'jstree-anchor jstree-search jstree-searchCheck'

    let container = $('#' + that.companyTreeId).find('.vision_tree')
    let _this = $('#' + this.companyTreeId)
      .find('.jstree-search')
      .eq(lenindex)
    let top = _this.offset().top - container.offset().top + container.scrollTop() - container.height() * 0.3
    container.animate({ scrollTop: top })
  }

  //拉取车辆数据
  select2Car() {
    var that = this
    $('#' + this.tcarNumberSelect2)
      .select2({
        language: 'zh-CN',
        placeholder: '请选择',
        allowClear: true,
        minimumInputLength: 2, //最少2个字符，select2才显示查询的内容
        ajax: {
          url: config.BaseURL + that.sourceCarUrl,
          dataType: 'json',
          delay: 50,
          method: 'POST',
          xhrFields: {
            withCredentials: true
          },
          data: function (params) {
            return {
              carNumber: params.term, // search term
              typeFlag: that.typeFlag
            }
          },
          processResults: function (data, params) {
            var options = new Array()
            // 小于10个数量才判断重复
            if (data.data.length <= 10) {
              let arr = []
              let sameCar = []
              // 判断相同的车牌号
              for (let index = 0; index < data.data.length; index++) {
                let car = data.data[index]
                if (arr.indexOf(car.carNumber) != -1) {
                  sameCar.push(car.carNumber)
                } else {
                  arr.push(car.carNumber)
                }
              }
              $(data.data).each(function (index, car) {
                if (sameCar.indexOf(car.carNumber) != -1) {
                  options.push({
                    id: car.deviceId,
                    text: car.carNumber + '[' + car.parentName + ']'
                  })
                } else {
                  options.push({
                    id: car.deviceId,
                    text: car.carNumber
                  })
                }
              })
            } else {
              $(data.data).each(function (index, car) {
                options.push({
                  id: car.deviceId,
                  text: car.carNumber
                })
              })
            }
            return {
              results: options //获取查询后的结果
            }
          },
          cache: true
        },
        templateResult: this.formatRepo
      })
      .on('select2:select', function (e) {
        var data = e.params.data
        that.deviceId = data.id
        if (data.text.indexOf('[') > 0) {
          that.carNumber = data.text.split('[')[0]
        } else {
          that.carNumber = data.text
        }
        that.sendParent()
      })
  }
  //select2 格式回调函数
  formatRepo(state) {
    if (!state.id) {
      return state.text
    }
    var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>')
    return $state
  }
  clearSelect2(obj) {
    obj.empty()
    obj.prepend("<option value=''>请选择</option>")
  }
  //擦除车牌号码所选值
  del_carNumber() {
    this.deviceId = ''
    this.carNumber = ''
    if (this.companyData) {
      this.companyData.deviceId = ''
      this.companyData.carNumber = ''
    }
    if (this.companyId) {
      this.queryCarListByCompanyId(this.companyId)
    } else {
      //采用简单粗暴的方法清除;官方推荐的方法失效
      var str = $("<span class='select2-selection__placeholder'>请选择</span>")
      $('#' + this.tcarNumberSelect2).val('')
      $('#select2-' + this.tcarNumberSelect2 + '-container').empty()
      $('#select2-' + this.tcarNumberSelect2 + '-container').attr('title', '')
      $('#select2-' + this.tcarNumberSelect2 + '-container').prepend(str)
    }
    this.sendParent()
  }
  //公司id拉取车辆
  queryCarListByCompanyId(companyId) {
    this.deviceId = ''
    this.carNumber = ''
    let reqdata = 'companyId=' + companyId
    this.jsonApiService.http('stats/carlist.html', reqdata).subscribe(data => {
      var carlist = data.data
      var selectdata = []
      for (var i = 0; i < carlist.length; i++) {
        var obj = {
          id: carlist[i].deviceId,
          text: carlist[i].carNumber
        }
        selectdata[i] = obj
      }

      var selectObj = $('#' + this.tcarNumberSelect2)
      this.clearSelect2(selectObj) //清除Select中的数据
      selectObj.select2({
        language: 'zh-CN',
        data: selectdata, //为Select添加数据
        templateResult: this.formatRepo
      })
      if (this.companyData && this.companyData.deviceId) {
        this.deviceId = this.companyData.deviceId
        this.carNumber = this.companyData.carNumber
        $('#' + this.tcarNumberSelect2)
          .val(this.companyData.deviceId)
          .trigger('change')
        this.sendParent()
      }
    })
  }
  //公司树模糊搜索	click
  companySearchBtn() {
    var that = this
    var value = $('#' + this.companyTreeId)
      .find('.treeSearchInput')
      .val()
    $('#' + this.companyTreeId)
      .find('.treeId')
      .eq(0)
      .jstree(true)
      .search(value)
    let searchResult = $('#' + this.companyTreeId).find('.jstree-search').length
    if (searchResult < 1) {
      that.jsonApiService.message('未搜索到结果')
      return
    }
    $('#' + this.companyTreeId)
      .find('.jstree-search')
      .each(function (index, obj) {
        if (index < 1) {
          //js树搜索定位到结果的第一个地方；
          let container = $('#' + that.companyTreeId).find('.vision_tree')
          let scrollTo = $(this)
          container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop() - 130)
          container.animate({
            scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() - container.height() * 0.3
          })
        }
      })
  }
}
